package com.youxin.busfoundation.utils.mybatis;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;


/** 
 * @author jinwen.you
 * 对分页的基本数据进行一个简单的封装 
 */  
@JsonInclude( JsonInclude.Include.NON_NULL )
public class BasePage<T> extends BaseRequest implements Cloneable{  
	private final int DEFAULT_PAGE_SIZE=20;
	private final int DEFAULT_MAX_PAGE_SIZE=200;
	
    /**
     * 页码，默认是第一页
     */
	@JsonProperty(value="page_no")
    private int pageNo = 1;
    /**
     * 每页显示的记录数，默认是20
     */
	@JsonProperty(value="page_size")
    private int pageSize = DEFAULT_PAGE_SIZE;
    /*
     * 总记录数
     */
	@JsonProperty(value="total_record")
    private long totalRecord;  
    /**
     * //总页数
     */
	@JsonProperty(value="total_page")
    private long totalPage;  
    /**
     * 对应的当前页记录
     */
    private List<T> results;  
    
	public List<T> getResults() {
		if(results==null)
		{
			results=new ArrayList<>();
		}
		return results;
	}

	public void setResults(List<T> results) {
		this.results = results;
		this.setLog(null);
	}
	
    public int getPageNo() {  
    	if(pageNo<1)
    		return 1;
       return pageNo;  
    }  
   
    public void setPageNo(Integer pageNo) {  
       this.pageNo = pageNo < 1 ? 1 : pageNo;  
    }  
   
    public int getPageSize() {  
    	if(pageSize<1)
    	{
    		return DEFAULT_PAGE_SIZE;
    	}
    	if(pageSize>DEFAULT_MAX_PAGE_SIZE)
    	{
    		return DEFAULT_MAX_PAGE_SIZE;
    	}
       return pageSize;  
    }  
   
    public void setPageSize(Integer pageSize) {  
        this.pageSize = pageSize < 1 ? DEFAULT_PAGE_SIZE : pageSize;  
    }  
   
    public long getTotalRecord() {  
       return totalRecord;  
    }  
   
    public void setTotalRecord(long totalRecord) {  
       this.totalRecord = totalRecord;  
       /**
        *在设置总页数的时候计算出对应的总页数，在下面的三目运算中加法拥有更高的优先级，所以最后可以不加括号。 
        */
       long totalPage = totalRecord%pageSize==0 ? totalRecord/pageSize : totalRecord/pageSize + 1;  
       this.setTotalPage(totalPage);  
    }  
   
    public long getTotalPage() {  
       return totalPage;  
    }  
   
    public void setTotalPage(long totalPage) {  
       this.totalPage = totalPage;  
    }
    
    /**
     * 是否最后一页
     * @return
     */
    @JsonProperty("is_last")
    public int isLast()
    {
    	return getPageNo()>=getTotalPage() ? 1 : 0;
    }
    
    /* (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
    	// TODO Auto-generated method stub
    	return super.clone();
    }

}